/* eslint-disable prefer-promise-reject-errors */
import app from './server'
const net = require("net");

var tcpClient = null;

export default {
    tcpSendData(arg){
        return new Promise((resolve, reject) => {
            const dataBuf = Buffer.from(arg, 'utf8');
            tcpClient.write(dataBuf);
            resolve();
        })
    },

    tcpClose(arg){
        return new Promise((resolve, reject) => {
            tcpClient.end();
            tcpClient.destroy();
            resolve()
        })
    },
    tcpConnect(event , arg){
        return new Promise((resolve, reject) => {
            tcpClient = net.createConnection({
                    host: arg.ip,
                    port: arg.port,
                    timeout : 3000
            }),
            tcpClient.on('connect', () => {
                tcpClient.on('data', (data) => {
                    event.sender.send('tcpReceiveData',data)
                });
                resolve("server connect success");
            });
            tcpClient.on('error', (err) => {
                event.sender.send('tcpError',err)
                reject(err);
            });
            tcpClient.on('end', (err) => {
                event.sender.send('tcpEnd',err)
                reject(err);
            });


        })
    }
}
